package com.jdy.haoduoaiteacher.view.calendar.adpter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.jdy.haoduoaiteacher.fragment.TabIndexFragment;
import com.jdy.haoduoaiteacher.model.HabitNumItem;
import com.jdy.haoduoaiteacher.util.Tools;
import com.jdy.haoduoaiteacher.view.calendar.CalendarUtil;
import com.jdy.haoduoaiteacher.view.calendar.adpter.WeekCalendarAdpter.OnDateSelectListener;
import com.jdy.haoduoaiteacher.view.calendar.fragment.MyCalendarFragment;
import com.jdy.haoduoaiteacher.view.calendar.utils.DateUtils;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * Created by Administrator on 2016/5/19 0019.
 */
public class MonthCalendarAdpter extends CalendarBaseAdpter {
  private List<View> views;
  private Context context;

  private Handler os = null;
  private int last_msg_tv_color;
  private Drawable yuanOfBlue, yuanOfYellow;
  private Drawable white;
  private int text_black;
  private int text_white;
  private final Drawable yuanOfBlack;

  public void setListHabitNumItem(ArrayList<HabitNumItem> mListHabitNumItem) {
    this.mListHabitNumItem = mListHabitNumItem;
  }

  private ArrayList<HabitNumItem>  mListHabitNumItem;

  public OnDateSelectListener mOnDateSelectListener;

  public void setOnDateSelectListener(OnDateSelectListener mOnDateSelectListener) {
    this.mOnDateSelectListener = mOnDateSelectListener;
  }

  private String strToDay = "";
  private ArrayList<String> list = new ArrayList<>();

  public MonthCalendarAdpter(List<View> views, Context context,
      ArrayList<String> list) {
    this.views = views;
    this.context = context;
    this.list = list;
    // 选中今天
    Calendar today = new GregorianCalendar();
    today.setTimeInMillis(System.currentTimeMillis());

    strToDay = DateUtils.getTagTimeStr(today);

    selectTime = DateUtils.getTagTimeStr(today);
    text_black = context.getResources().getColor(R.color.black_deep);
    last_msg_tv_color = context.getResources().getColor(
        R.color.last_msg_tv_color);
    text_white = context.getResources().getColor(R.color.white);
    yuanOfBlue = context.getResources().getDrawable(R.drawable.yuan);
    yuanOfYellow = context.getResources().getDrawable(R.drawable.yuan_yellow);
    yuanOfBlack = context.getResources().getDrawable(
        R.drawable.calendar_background);
    white = context.getResources().getDrawable(R.drawable.white);
  }

  public void setHandler(Handler os) {
    this.os = os;
  }

  @Override
  public int getCount() {
    return 2400;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
    return view == object;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {

  }

  @Override
  public Object instantiateItem(ViewGroup container, final int position) {
    ViewGroup view = (ViewGroup) views.get(position % views.size());
    int index = container.indexOfChild(view);
    if (index != -1) {
      container.removeView(view);
    }
    try {
      container.addView(view);
    } catch (Exception e) {

    }
    refresh(view, position, list);
    return view;
  }

  public void getTimeList(ArrayList<String> list) {
    this.list = list;
  }

  private final static int MONTH_TAG = 5 << 24;
  private final static int YELLOW_TAG = 6 << 24;

  /**
   * 提供对外的刷新接口
   */
  public void refresh(ViewGroup view, int position, ArrayList<String> list) {
    // 给view 填充内容

    // 设置开始时间为本周日
    Calendar today = new GregorianCalendar();
    today.setTimeInMillis(System.currentTimeMillis());
    // 距离当前时间的月数
    int month = 1200 - position;
    today.add(Calendar.MONTH, -month);
    view.setTag(MONTH_TAG, today.get(Calendar.MONTH) + "");
    // 找到这个月的第一天所在星期的周日
    today.add(Calendar.DAY_OF_MONTH, -(today.get(Calendar.DAY_OF_MONTH) - 1));

    int day_of_week = today.get(Calendar.DAY_OF_WEEK) - 1;
    if (day_of_week == 0) {
      day_of_week = 7;
    }
    today.add(Calendar.DATE, -day_of_week);

    render(view, today);
  }

  ViewGroup mViewGroup;

  /**
   * 渲染page中的view：7天
   */
  @SuppressWarnings("deprecation")
  private void render(final ViewGroup view1, final Calendar today) {
    mViewGroup = view1;
    // 一页显示一个月+7天，为42；
    for (int b = 0; b < 6; b++) {
      final ViewGroup view = (ViewGroup) view1.getChildAt(b);
      for (int a = 0; a < 7; a++) {
        final int dayOfMonth = today.get(Calendar.DAY_OF_MONTH);
        final ViewGroup dayOfWeek = (ViewGroup) view.getChildAt(a);
        ((TextView) dayOfWeek.findViewById(R.id.gongli)).setText(dayOfMonth
            + "");
        String str = "";
        try {
          str = new CalendarUtil().getChineseDay(today.get(Calendar.YEAR),
              today.get(Calendar.MONTH) + 1, today.get(Calendar.DAY_OF_MONTH));
        } catch (Exception e) {

        }
        ((ImageView) dayOfWeek.findViewById(R.id.imv_point))
            .setVisibility(View.INVISIBLE);
        // String str =
        if (str.equals("初一")) {// 如果是初一，显示月份
          str = new CalendarUtil().getChineseMonth(today.get(Calendar.YEAR),
              today.get(Calendar.MONTH) + 1, today.get(Calendar.DAY_OF_MONTH));
        }
        ((TextView) dayOfWeek.findViewById(R.id.nongli)).setText(str);
        if (list.contains(DateUtils.getTagTimeStr(today))) {
          ((ImageView) dayOfWeek.findViewById(R.id.imv_point))
              .setVisibility(View.VISIBLE);
          ((ImageView) dayOfWeek.findViewById(R.id.imv_point))
              .setImageResource(R.drawable.calendar_item_point);
        } else {
          ((ImageView) dayOfWeek.findViewById(R.id.imv_point))
              .setVisibility(View.INVISIBLE);
        }
        dayOfWeek.setTag(DateUtils.getTagTimeStr(today));


        if (TabIndexFragment.mListHabitNumItem!=null && !TabIndexFragment.mListHabitNumItem.isEmpty()) {
          for (HabitNumItem item : TabIndexFragment.mListHabitNumItem) {
            if (item.dateStr.contains(DateUtils.getTagTimeStr(today))) {
              if (item.num > 0) {
                dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.VISIBLE);
                switch (item.num) {
                  case 1:
                    ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.one_blue_pt);
                    break;
                  case 2:
                    ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.two_blue_pt);
                    break;
                  case 3:
                    ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_blue_pt);
                    break;
                  default:
                    ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_blue_pt);
                    break;
                }
              } else {
                dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
              }
              break;
            } else {
              dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
            }
          }
        } else {
          dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
        }

        dayOfWeek.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            is = true;
            // TODO:发消息，告诉Activity我改变选中的日期了
            if (MonthCalendarAdpter.this.os != null) {
              os.sendEmptyMessage(MyCalendarFragment.change);
            }

            selectTime = dayOfWeek.getTag().toString();
            today.add(Calendar.DATE, -42);// 因为已经渲染过42天，所以today往前推42天，
                                          // 代表当前page重绘；

            //
            // 恢复上个选中的day的状态
            if (day != null) {
              day.findViewById(R.id.cal_container).setBackgroundDrawable(white);
              ((TextView) day.findViewById(R.id.gongli))
                  .setTextColor(text_black);
              // 特殊情况
              if (strToDay.equals(tag)) {
                day.findViewById(R.id.cal_container).setBackgroundDrawable(
                    yuanOfBlack);
                ((TextView) day.findViewById(R.id.gongli))
                    .setTextColor(text_black);
                ((TextView) day.findViewById(R.id.nongli))
                    .setTextColor(last_msg_tv_color);

              } else {
                day.findViewById(R.id.cal_container).setBackgroundDrawable(
                    white);
                ((TextView) day.findViewById(R.id.gongli))
                    .setTextColor(text_black);
                ((TextView) day.findViewById(R.id.nongli))
                    .setTextColor(last_msg_tv_color);
              }
            }
            // 变为红色

            if (view1.getTag(YELLOW_TAG) != null) {
              ((View) view1.getTag(YELLOW_TAG)).setBackgroundDrawable(white);

              TextView tvv = (TextView) ((View) view1.getTag(YELLOW_TAG))
                  .findViewById(R.id.gongli);
              tvv.setTextColor(text_black);

            }

            dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
                yuanOfBlue);

            if (TabIndexFragment.mListHabitNumItem!=null && !TabIndexFragment.mListHabitNumItem.isEmpty()) {
              for (HabitNumItem item : TabIndexFragment.mListHabitNumItem) {
                if (item.dateStr.contains(selectTime)) {
                  if (item.num > 0) {
                    dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.VISIBLE);
                    switch (item.num) {
                      case 1:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.one_white_pt);
                        break;
                      case 2:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.two_white_pt);
                        break;
                      case 3:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_white_pt);
                        break;
                      default:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_white_pt);
                        break;
                    }
                  } else {
                    dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
                  }
                  break;
                } else {
                  dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
                }
              }
            }

            ((TextView) dayOfWeek.findViewById(R.id.gongli))
                .setTextColor(text_white);
            ((TextView) dayOfWeek.findViewById(R.id.nongli))
                .setTextColor(text_white);

            dayOfWeek.invalidate();

            if (mOnDateSelectListener != null) {
              mOnDateSelectListener.onDateSelected(selectTime);
            }
            render(view1, today);
            is = false;

          }
        });

        if (strToDay.equals(DateUtils.getTagTimeStr(today))) {
          dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
              yuanOfBlack);

          ((TextView) dayOfWeek.findViewById(R.id.gongli))
              .setTextColor(text_black);
          ((TextView) dayOfWeek.findViewById(R.id.nongli))
              .setTextColor(last_msg_tv_color);
          if (!selectTime.equals(strToDay)) {
            today.add(Calendar.DATE, 1);
            continue;
          }
        } else {
          dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
              white);

          ((TextView) dayOfWeek.findViewById(R.id.gongli))
              .setTextColor(text_black);
        }

        boolean hasDrawYellow = false;
        // 不是当前月的显示为灰色
        if ((Integer.parseInt((String) view1.getTag(MONTH_TAG))) != today
            .get(Calendar.MONTH)) {
          ((TextView) dayOfWeek.findViewById(R.id.gongli))
              .setTextColor(last_msg_tv_color);
          if ((Integer.parseInt((String) view1.getTag(MONTH_TAG))) > today
              .get(Calendar.MONTH)) {
            // 下个月
            dayOfWeek.setOnClickListener(lastLister);
          } else {
            // 上个月
            dayOfWeek.setOnClickListener(nextLister);
          }
          today.add(Calendar.DATE, 1);
          continue;
        } else {

          String todayFormat = DateUtils.getTagTimeStr(today);
          if (todayFormat
              .subSequence(todayFormat.length() - 3, todayFormat.length())
              .toString().contains("-01")) {
            dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
                yuanOfYellow);

            view1
                .setTag(YELLOW_TAG, dayOfWeek.findViewById(R.id.cal_container));

            hasDrawYellow = true;
          }

          dayOfWeek.setAlpha(1.0f);
        }
        // 如果是选中天的话显示为红色
        if (selectTime.equals(DateUtils.getTagTimeStr(today))) {

          if (view1.getTag(YELLOW_TAG) != null) {
            ((View) view1.getTag(YELLOW_TAG)).setBackgroundDrawable(white);

            TextView tvv = (TextView) ((View) view1.getTag(YELLOW_TAG))
                .findViewById(R.id.gongli);
            tvv.setTextColor(text_black);

          }

          dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
              yuanOfBlue);

          if (TabIndexFragment.mListHabitNumItem!=null && !TabIndexFragment.mListHabitNumItem.isEmpty()) {
            for (HabitNumItem item : TabIndexFragment.mListHabitNumItem) {
              if (item.dateStr.contains(selectTime)) {
                if (item.num > 0) {
                  dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.VISIBLE);
                  switch (item.num) {
                    case 1:
                      ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.one_white_pt);
                      break;
                    case 2:
                      ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.two_white_pt);
                      break;
                    case 3:
                      ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_white_pt);
                      break;
                    default:
                      ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_white_pt);
                      break;
                  }
                } else {
                  dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
                }
                break;
              } else {
                dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
              }
            }
          }

          ((TextView) dayOfWeek.findViewById(R.id.gongli))
              .setTextColor(text_white);
          ((TextView) dayOfWeek.findViewById(R.id.nongli))
              .setTextColor(text_white);

          if (strToDay.equals(DateUtils.getTagTimeStr(today))) {

            if (view1.getTag(YELLOW_TAG) != null) {
              ((View) view1.getTag(YELLOW_TAG)).setBackgroundDrawable(white);

              TextView tvv = (TextView) ((View) view1.getTag(YELLOW_TAG))
                  .findViewById(R.id.gongli);
              tvv.setTextColor(text_black);

            }

            dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
                yuanOfBlue);

            if (TabIndexFragment.mListHabitNumItem!=null && !TabIndexFragment.mListHabitNumItem.isEmpty()) {
              for (HabitNumItem item : TabIndexFragment.mListHabitNumItem) {
                if (item.dateStr.contains(selectTime)) {
                  if (item.num > 0) {
                    dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.VISIBLE);
                    switch (item.num) {
                      case 1:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.one_white_pt);
                        break;
                      case 2:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.two_white_pt);
                        break;
                      case 3:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_white_pt);
                        break;
                      default:
                        ((ImageView)dayOfWeek.findViewById(R.id.imv_numpoint)).setImageResource(R.drawable.three_white_pt);
                        break;
                    }
                  } else {
                    dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
                  }
                  break;
                }else {
                  dayOfWeek.findViewById(R.id.imv_numpoint).setVisibility(View.GONE);
                }
              }
            }

            ((TextView) dayOfWeek.findViewById(R.id.gongli))
                .setTextColor(text_white);
            ((TextView) dayOfWeek.findViewById(R.id.nongli))
                .setTextColor(text_white);
          }

          day = dayOfWeek;
          if (MonthCalendarAdpter.this.os != null) {
            Message message = os.obtainMessage();
            message.obj = b;
            message.what = MyCalendarFragment.change2;
            os.sendMessage(message);
          }
          tag = selectTime;
        } else {

          if (!hasDrawYellow)
            dayOfWeek.findViewById(R.id.cal_container).setBackgroundDrawable(
                white);

          ((TextView) dayOfWeek.findViewById(R.id.gongli))
              .setTextColor(text_black);
          ((TextView) dayOfWeek.findViewById(R.id.nongli))
              .setTextColor(last_msg_tv_color);
        }
        today.add(Calendar.DATE, 1);
      }
    }

  }

  View.OnClickListener nextLister = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (MonthCalendarAdpter.this.os != null) {
        Message message = os.obtainMessage();
        message.what = MyCalendarFragment.pagerNext;
        os.sendMessage(message);
      }
    }
  };
  View.OnClickListener lastLister = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (MonthCalendarAdpter.this.os != null) {
        Message message = os.obtainMessage();
        message.what = MyCalendarFragment.pagerLast;
        os.sendMessage(message);
      }
    }
  };

  private ViewGroup day = null;

  public ViewGroup getDay() {
    return day;
  }

  private String tag = "";

  public String getSelectTime() {
    return selectTime;
  }

  public void setSelectTime(String selectTime) {
    this.selectTime = selectTime;
  }

  public void performClick() {

    if (mViewGroup!=null) {
      for (int b = 0; b < 6; b++) {
        final ViewGroup view = (ViewGroup) mViewGroup.getChildAt(b);
        for (int a = 0; a < 7; a++) {
          final ViewGroup dayOfWeek = (ViewGroup) view.getChildAt(a);
          if (Tools.isNotEmpty(dayOfWeek.getTag().toString())) {
            dayOfWeek.performClick();
            break;
          }
        }
      }
    }




//    if (mOnDateSelectListener != null) {
//      mOnDateSelectListener.onDateSelected(selectTime);
//    }
  }

}
